<template>
  <view class="home">
    <view>
      <form @submit="formSubmit">
        <view class="form">
          <view class="content paddingBotNone">
            <view class="title">服务对象身份信息</view>
            <view :class="[identityItem.length < 4 ? 'disBlockBox textLeft' : 'disBlockBox', 'indentContent']">
              <view class="indentTitle">关系</view>
              <view
                v-for="item in identityItem"
                :key="item.value"
                :class="['disBlockKid', item.value === formData.identity ? 'chose' : null]"
                @click="choseUser(item)"
              >
                <text :class="['disBlock']">
                  {{ item.label }}
                </text>
                <img v-show="item.value === formData.identity" class="choseImg" :src="curIcon" alt="" />
              </view>
            </view>
            <view v-if="formData.identity && formData.identity !== 1" class="userHistory">
              <span>成员：</span>
              <view
                v-for="item in historyList"
                :key="item.memberId"
                :class="[item.memberId === historyCur ? 'spans historyCur' : 'spans']"
                @click="getUserInfo(item)"
                >{{ item.memberName }}
              </view>
              <view :class="[!historyCur && historyCur !== 0 ? 'spans historyCur' : 'spans']" @click="addUser"
                >新增+</view
              >
            </view>
            <view class="inputBox">
              <view
                v-show="focusInp === 'name' && !isAuthen && formData.name"
                class="clearInp"
                @click.native.stop="clearFun('name')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">姓名</span>
              <view>
                <input
                  v-model="formData.name"
                  class="uni-input lineHeight86"
                  name="name"
                  placeholder="请输入姓名"
                  :disabled="isAuthen"
                  placeholder-class="phcolor"
                  @focus="vauleEmpty('name')"
                  @blur="unFocus"
                />
              </view>
              <view class="clear"></view>
            </view>
            <view
              v-if="serviceIncludeScene === 'isHaveInsurance' || serviceIncludeScene === 'isHaveInsurDoctorOrPhy'"
              class="inputBox"
            >
              <view
                v-show="focusInp === 'idCard' && formData.idCard"
                class="clearInp"
                @click.native.stop="clearFun('idCard')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">身份证</span>
              <input
                v-model="formData.idCard"
                type="idcard"
                class="uni-input lineHeight86"
                name="idCard"
                placeholder="请输入身份证号"
                placeholder-class="phcolor"
                maxlength="18"
                :disabled="isAuthen"
                @change="idCardChange($event, formData.idCard)"
                @focus="vauleEmpty('idCard')"
                @blur="unFocus"
              />
              <view v-show="isAuthen" class="idAuthen">实名</view>
              <view class="clear"></view>
            </view>
            <view
              v-if="serviceIncludeScene === 'isHaveDoctorOrPhy'"
              :class="[isAuthen || (!isAddType && formData.idCard) ? 'inputBox pointNone' : 'inputBox']"
            >
              <span class="name lineHeight86">性别</span>
              <view class="sickBox">
                <view
                  v-for="item in sexItem"
                  :key="item.value"
                  :class="[item.value === formData.sex ? 'chose sickBtn' : 'sickBtn']"
                  @click="choseSex(item.value)"
                >
                  {{ item.name }}
                  <view v-show="item.value === formData.sex" class="cur"><img :src="curIcon" /></view>
                </view>
              </view>
              <view class="clear"></view>
            </view>
            <view v-if="serviceIncludeScene === 'isHaveDoctorOrPhy'" class="inputBox">
              <span class="name lineHeight86">生日</span>
              <view class="uni-list">
                <view class="uni-list-cell">
                  <view
                    :class="[
                      isAuthen || (!isAddType && formData.idCard) ? 'uni-list-cell-db pointNone' : 'uni-list-cell-db'
                    ]"
                  >
                    <picker
                      class="pickStyle"
                      mode="date"
                      name="birthday"
                      :value="formData.birthday"
                      :disabled="isAuthen || serviceIncludeScene === 'isHaveInsurance'"
                      :start="startDate"
                      :end="endDate"
                      @change="bindDateChange"
                    >
                      <view class="uni-input">
                        <span v-if="formData.birthday">{{ formData.birthday }}</span>
                        <span v-else class="grey">请选择生日</span>
                      </view>
                      <view class="inputIcon"><img :src="require('./../images/icons/right.png')" /></view>
                    </picker>
                  </view>
                </view>
              </view>
              <view class="clear"></view>
            </view>
            <view
              v-if="serviceIncludeScene === 'isHaveInsurance'"
              :class="[isAuthen || isHavePhone ? 'inputBox pointNone' : 'inputBox']"
            >
              <span class="name lineHeight86">联系方式</span>
              <view class="sickBox marginBottom20">
                <view
                  v-for="item in phoneTypeItem"
                  :key="item.value"
                  :class="[item.value === formData.phoneType ? 'chose sickBtn' : 'sickBtn']"
                  @click="chosePhoneType(item.value)"
                >
                  {{ item.name }}
                  <view v-show="item.value === formData.phoneType" class="cur"><img :src="curIcon" /></view>
                </view>
              </view>
              <view class="clear"></view>
            </view>
            <view
              v-if="formData.phoneType === 0 && serviceIncludeScene === 'isHaveInsurance'"
              class="inputBox messageCodeBox"
            >
              <view
                v-show="focusInp === 'machineNumber'"
                class="clearInp"
                @click.native.stop="clearFun('machineNumber')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">其他号码</span>
              <label class="messageInputWith">
                <input
                  v-model="formData.machineNumber"
                  class="uni-input lineHeight86"
                  name="machineNumber"
                  maxlength="20"
                  :disabled="!isAddType && isHaveMachineNumber"
                  placeholder="请输入,如：010-88888888"
                  placeholder-class="phcolor"
                  @focus="vauleEmpty('machineNumber')"
                  @blur="unFocus"
                />
              </label>
              <view class="clear"></view>
            </view>
            <view v-else class="inputBox messageCodeBox">
              <view
                v-show="focusInp === 'phone' && formData.phone"
                class="clearInp"
                @click.native.stop="clearFun('phone')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">手机号</span>
              <label class="messageInputWith">
                <input
                  v-model="formData.phone"
                  type="number"
                  class="uni-input lineHeight86"
                  name="phone"
                  maxlength="11"
                  :disabled="!isAddType && isHavePhone"
                  placeholder="请输入手机号"
                  placeholder-class="phcolor"
                  @focus="vauleEmpty('phone')"
                  @blur="unFocus"
                />
              </label>
              <view class="clear"></view>
            </view>
            <view class="tips">
              为了向您和家人提供个性化健康管理服务，我们需要获知服务对象的性别、年龄等信息。如需帮助，请联系人工客服
              <span class="tellNum">400-010-1516</span>。
            </view>
          </view>
        </view>
        <fixed-bottom-button v-if="isLogin">
          <view class="uni-btn-v">
            <button form-type="submit">提交</button>
          </view>
        </fixed-bottom-button>
      </form>
    </view>
    <!-- 滚动弹窗，阅读协议 -->
    <view v-if="artIdArr.length > 0">
      <readArticleScrollPop
        ref="artScroll"
        :idArr="artIdArr"
        @artPopCenter="artPopCenter"
        @getArticleTitle="getArticleTitle"
      >
        <view v-if="artTitleArr.length > 0" class="footbox">
          <view class="agreeBox" @click="readArticle">
            <span class="noClick"><checkbox :checked="argeeBoolean" /></span>
            阅读并同意
            <span class="blue">《{{ artTitleArr[0].title }}》</span>
          </view>
        </view>
      </readArticleScrollPop>
    </view>
  </view>
</template>
<script>
import { hospitalId, articleArr, registerSource } from '@/common/baseUrl.js';
import { getPatientId } from '@/utils/auth.js';
import { getInfoByIdCard, getAge as getAgeByBirthday } from '@/utils/optimize.js';
import fixedBottomButton from '@/components/fixedBottomBtn';
// 引入统计
import { tongji } from '@/utils/tools.js';
import {
  getUserInfoByPatientId,
  getFamilyMember,
  getPatientIdByIdCard,
  sendUserInfoForm,
  bindPatients,
  addFamilyMember,
  getRealNameResult,
  getServerPackInof,
  createServiceOrder,
  getInsuranceOrder
} from '@/api/join.js';
import curIcon from '@/static/icon/cur.png';
import clearIconImg from '@/static/icon/clearIcon.png';
import pCheckedIcon from '@/static/icon/p-checked.png';
import pNoCheckedIcon from '@/static/icon/p-nochecked.png';
import { mapState } from 'vuex';
import readArticleScrollPop from '@/components/readArticleScrollPop';
let graceChecker = require('../../common/graceChecker.js');
import { inquiryMixin } from '@/common/mixin.js';

export default {
  components: {
    fixedBottomButton,
    readArticleScrollPop
  },
  mixins: [inquiryMixin],
  data() {
    const currentDate = this.getDate({
      format: true
    });
    return {
      curIcon: curIcon,
      pCheckedIcon,
      pNoCheckedIcon,
      closeIcon: clearIconImg,
      identityItem: [],
      historyItem: {
        spouseItem: [],
        parentItem: [],
        childrenItem: []
      },
      historyList: [],
      historyCur: '',
      sickList: [],
      formData: this.$store.getters.storeFormData,
      isAuthen: false,
      ownInfo: {},
      sickInitList: [],
      sickAllList: [],
      searchChoseList: [],
      clickChoseList: [],
      choseIllList: [],
      loginPatientId: getPatientId(),
      submitPatientId: '',
      familyUserData: [],
      addressComData: [], // 省市区组件使用格式，提交信息的时候需要转为对象格式

      // 社区小程序
      isLogin: wx.getStorageSync('token') || false,
      idArr: articleArr,
      articlePop: false,
      agree: false,
      artTitleArr: [],
      price: '',
      date: currentDate,
      sexItem: [
        {
          name: '男',
          value: 1
        },
        {
          name: '女',
          value: 0
        }
      ],
      phoneTypeItem: [
        {
          name: '手机号',
          value: 1
        },
        {
          name: '其他号码',
          value: 0
        }
      ],
      show: true,
      idCardPhoneIdUnequal: false, // 手机号获取的patientId和身份证获取的patientId不一致
      serviceInfo: {},
      argeeBoolean: false,
      isAddType: '', // 用于提交时判断是否为新增用户操作
      artIdArr: [],
      isHavePhone: true, // 历史用户中是否已存在联系方式
      isHaveMachineNumber: '', // 历史用户中是否已存在其他联系方式
      getHistoryPid: '',
      serviceIncludeScene: 'isHaveDoctorOrPhy', // isHaveInsurance=>仅含保险的场景 isHaveDoctorOrPhy=>仅含体检/视频医生的场景（通用） isHaveInsurDoctorOrPhy=>含保险+ 体检/视频医生
      focusInp: null,
      timer: null,
      timerTime: false
    };
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate('end');
    },
    ...mapState('join', {
      serviceId: 'communityServiceId'
    })
  },
  watch: {
    'formData.idCard': {
      handler: function () {
        if (this.formData.idCard && this.formData.idCard.length < 18) {
          this.formData.sex = '';
          this.formData.birthday = '';
        } else if (this.formData.idCard && this.formData.idCard.length === 18) {
          this.formData.sex = getInfoByIdCard(this.formData.idCard, 2);
          this.formData.birthday = getInfoByIdCard(this.formData.idCard, 1);
        }
      },
      immediate: true
    },
    'formData.phone': {
      handler: function () {
        if (this.formData.phone && this.formData.phone.length === 11 && !this.formData.idCard) {
          this.initUserInfoByPhone();
        }
      },
      immediate: true
    },
    isAuthen: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          const self = this;
          setTimeout(function () {
            self.focusInp = null;
          }, 200);
          uni.hideKeyboard();
        }
      }
    }
  },
  onLoad(options) {
    this.getHistoriesUser();
    if (options && options.fromPage === '1') {
      this.formData.identity = '';
      this.addUser();
    }
    if (options && options.price) {
      this.price = options.price || 0;
    }
    // 区分疾病，热门疾病和搜索列表中的疾病
  },
  async onShow() {
    this.isLogin = wx.getStorageSync('token') || false; // 登录返回后数据重新拉取更新
    this.formData.identity = '';
    await this.addUser();
    this.getUserData();
  },
  mounted() {
    console.log('我是hospitalId', hospitalId);
  },
  methods: {
    vauleEmpty(key) {
      console.log('key', key);
      // clearTimeout(this.timer);
      // this.timer = null;
      const self = this;
      if (this.timerTime) {
        setTimeout(function () {
          self.timerTime = !self.timerTime;
        }, 200);
        return;
      }
      this.focusInp = key;
    },
    clearFun(key) {
      const self = this;
      self.$set(self.formData, key, '');
      let data = JSON.parse(JSON.stringify(this.formData));
      data[key] = null;
      this.$nextTick(() => {
        self.formData = data;
      });
      this.$forceUpdate();
      if (key === 'idCard') {
        self.idCardChange('', '', 'clear');
      }
    },
    unFocus() {
      this.focusInp = null;
    },
    async initUserInfoByPhone() {
      const { data: patientId } = await getPatientIdByIdCard({
        phone: this.formData.phone,
        idCard: ''
      });
      if (patientId) {
        // 20220415 原流程
        // const { data: userInfo } = await getUserInfoByPatientId(patientId);
        // this.initFormValue(userInfo);
        console.log('initUserInfoByPhone this.formData.patientId:', this.formData.patientId);
        if (this.formData.patientId && this.formData.patientId !== patientId) {
          uni.showToast({ title: '手机号已存在', icon: 'none' });
        } else {
          const { data: userInfo } = await getUserInfoByPatientId(patientId);
          this.initFormValue(userInfo);
        }
      }
    },
    // eslint-disable-next-line complexity
    async getServiceInfo() {
      uni.showToast({ title: '加载中', icon: 'loading', duration: 15000, mask: true });
      const { data } = await getServerPackInof(this.serviceId || 160);
      uni.hideToast();
      this.serviceInfo = data[0];
      // const isHavePro = this.serviceInfo.insurancePackagePros
      //   .map((item) => item.insuranceServices.map((kid) => kid.type))
      //   .flat(Infinity);
      let isHavePro = [];
      this.serviceInfo.insurancePackagePros.forEach((item) => {
        item.insuranceServices.forEach((kitItem) => {
          isHavePro.push(kitItem.type);
        });
      });
      // 1.含保险 + 视频医生/体检 isHaveInsurance   isHaveDoctorOrPhy  isHaveInsurDoctorOrPhy 这里
      if (isHavePro.length > 0 && isHavePro.includes(1) && (isHavePro.includes(2) || isHavePro.includes(4))) {
        this.serviceIncludeScene = 'isHaveInsurDoctorOrPhy';
      } else if (isHavePro.length > 0 && isHavePro.includes(1)) {
        this.serviceIncludeScene = 'isHaveInsurance';
      } else if (isHavePro.length > 0 && (isHavePro.includes(2) || isHavePro.includes(4))) {
        this.serviceIncludeScene = 'isHaveDoctorOrPhy';
      }
      console.log('服务包包含产品类型', this.serviceIncludeScene);
      this.artIdArr = [];
      const proArticle = this.serviceInfo.insurancePackageSpecs.find((item) => item.type === 7);
      proArticle ? this.artIdArr.push(proArticle.articleId) : (this.artIdArr = []);
      let identityItem = this.serviceInfo.relationDicts || [];
      identityItem.map((item) => {
        item.click = false;
        return item;
      });
      const type2 = identityItem.findIndex((item) => item.value === 2);
      const type3 = identityItem.findIndex((item) => item.value === 3);
      if (type2 > -1 && type3 > -1) {
        [identityItem[type2], identityItem[type3]] = [identityItem[type3], identityItem[type2]];
      }
      console.log('identityItem:', identityItem);
      this.identityItem = identityItem;
      if (identityItem.length === 1) {
        this.choseUser(identityItem[0]);
      }
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 120;
      } else if (type === 'end') {
        year = year + 0;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    bindDateChange: function (e) {
      this.formData.birthday = e.target.value;
    },
    getUserData() {
      const self = this;
      const patientId = wx.getStorageSync('patientid');
      getUserInfoByPatientId(patientId).then((res) => {
        if (res.code === 0 && res.data) {
          self.ownInfo = res.data;
          this.getServiceInfo();
        }
      });
    },
    filterDisease(val) {
      // 匹配有没有热门疾病数据 sick
      return val.map((item) => {
        return item.id;
      });
    },
    getOwnData() {
      // 和底下分开，为了是减少一次接口请求，本人不需要即时请求
      this.initFormValue(this.ownInfo);
    },
    async getUserInfo(item) {
      this.addUser();
      this.historyCur = item.memberId;
      this.isAuthen = await getUserInfoByPatientId(item.memberId).then((res) => {
        if (res.code === 0) {
          this.initFormValue(res.data);
        }
      });
    },
    initFormValue(data, refer) {
      const self = this;
      // if (!refer) {
      this.isAddType = false;
      // }
      data.memberName ? (self.formData.name = data.memberName) : (self.formData.name = data.name);
      self.formData.patientId = data.patientId;
      self.formData.idCard = data.idCard;
      self.formData.phone = data.phone;
      self.formData.address = data.address;
      self.getHistoryPid = data.patientId || '';
      self.formData.machineNumber = data.machineNumber || '';
      self.formData.birthday = data.birthday;
      self.formData.phoneType = data.phone ? 1 : data.machineNumber ? 0 : '';
      self.formData.sex = data.sex;
      if (data.diseases && data.diseases.length > 0) {
        self.formData.diseases = self.filterDisease(data.diseases);
        self.formData.sick = 2;
      } else {
        self.formData.diseases = [];
        self.formData.sick = '';
      }
      if (data.realNameAuthenticationPassed === 1) {
        this.isAuthen = true;
      }
      data.phone ? (this.isHavePhone = data.phone) : (this.isHavePhone = false);
      data.machineNumber ? (this.isHaveMachineNumber = data.machineNumber) : (this.isHaveMachineNumber = false);
    },
    async idCardChange(e, val, isClear) {
      const self = this;
      if (isClear && this.isAuthen) {
        setTimeout(function () {
          self.formData.idCard = '';
          return false;
        }, 400);
        return;
      }
      if (val && val.length === 18) {
        this.isAuthen = false;
        let patientId = await getPatientIdByIdCard({ phone: '', idCard: this.formData.idCard }).then((res) => {
          if (res.code === 0) {
            return res.data;
          } else {
            uni.showToast({ title: res.message, icon: 'none' });
          }
          return false;
        });
        if (patientId) {
          this.submitPatientId = patientId;
          getUserInfoByPatientId(patientId).then((res) => {
            if (res.code === 0) {
              self.initFormValue(res.data, 'fromIdCardChange');
              if (res.data.realNameAuthenticationPassed && res.data.realNameAuthenticationPassed === 1) {
                self.isAuthen = true;
                // self.formData.name = res.data.name || '';
                // self.formData.machineNumber = res.data.machineNumber || '';
                // self.formData.phone = res.data.phone || '';
                // self.initFormValue(res.data);
              }
            }
          });
        }
      } else if (val && val.length > 0) {
        uni.showToast({ title: '请输入正确的身份证号', icon: 'none' });
      }
    },
    async getHistoriesUser() {
      const self = this;
      const patientId = wx.getStorageSync('patientid');
      await getFamilyMember(patientId).then((res) => {
        self.historyItem = {
          spouseItem: [],
          parentItem: [],
          childrenItem: []
        };
        // "relationShip":1,//关系 1本人 2配偶 3 父母 4 子女
        if (res.code === 0 && res.data) {
          this.familyUserData = res.data;
          res.data.forEach((item) => {
            if (item.relation === 2) {
              self.historyItem.spouseItem.push(item);
            }
            if (item.relation === 3) {
              self.historyItem.parentItem.push(item);
            }
            if (item.relation === 4) {
              self.historyItem.childrenItem.push(item);
            }
          });
        }
      });
    },
    // Monday Tuesday Wednesday Thursday Friday Saturday Sunday
    async choseUser(val) {
      console.log(23234234, val, this.formData.identity);
      let id = val.value;
      if (id === this.formData.identity) {
        return;
      }
      this.show = true;

      this.isAddType = false;
      this.historyItem = {
        spouseItem: [],
        parentItem: [],
        childrenItem: []
      };
      this.historyList = [];
      await this.getHistoriesUser();
      this.addUser();
      this.isAuthen = false;
      this.historyCur = '';
      let getChoseItem = this.identityItem.find((item) => {
        return item.value === id;
      });
      this.formData.identity = getChoseItem.value;
      if (id === 1) {
        this.getOwnData();
      }
      if (id === 2) {
        this.historyList = this.historyItem.spouseItem;
      }
      if (id === 3) {
        this.historyList = this.historyItem.parentItem;
      }
      if (id === 4) {
        this.historyList = this.historyItem.childrenItem;
      }
      this.historyList = [...new Set(this.historyList)];
    },
    addUser() {
      this.historyCur = '';
      let temporaryIndentity = this.formData.identity;
      this.formData = {
        identity: '', // 为谁加入
        name: '', // 姓名
        idCard: '', // 身份证
        phone: '', // 手机号
        sick: '', // 是否患病
        sickList: [], // 患病了，都有什么病
        address: { areaId: null, street: null, cityId: null, provinceId: null }, // 城市[10010, 10031]
        sex: '', // 性别
        birthday: '', // 生日
        phoneType: ''
      };
      this.formData.identity = temporaryIndentity;
      this.isAuthen = false;
      this.isAddType = true;
      this.isHavePhone = false;
      this.getHistoryPid = '';
    },
    checkRequestFun(formValue) {
      if (!this.formData.identity) {
        return '请选择为谁加入万户健康项目';
      }
      // 定义表单规则
      let rule = [
        {
          name: 'name',
          checkType: 'zhDecimal',
          checkRule: '1,20',
          errorMsg: '请填写正确姓名(1-20个汉字)'
        },
        {
          name: 'idCard',
          checkType: 'idcard',
          checkRule: '',
          isPassCheck:
            !this.serviceIncludeScene ||
            this.serviceIncludeScene === '' ||
            this.serviceIncludeScene === 'isHaveDoctorOrPhy',
          errorMsg: '请填写正确身份证号'
        },
        {
          name: 'sex',
          checkType: 'notnull',
          checkRule: '',
          isPassCheck: !(this.serviceIncludeScene === 'isHaveDoctorOrPhy'),
          errorMsg: '请选择性别'
        },
        {
          name: 'birthday',
          checkType: 'notnull',
          checkRule: '',
          isPassCheck: !(this.serviceIncludeScene === 'isHaveDoctorOrPhy'),
          errorMsg: '请选择生日'
        },
        {
          name: 'phoneType',
          checkType: 'notnull',
          checkRule: '',
          isPassCheck: !(this.serviceIncludeScene === 'isHaveInsurance'),
          errorMsg: '请选择联系方式'
        },
        {
          name: 'phone',
          checkType: 'phoneno',
          checkRule: '',
          isPassCheck:
            (this.serviceIncludeScene === 'isHaveInsurance' && this.formData.phoneType === 0) ||
            this.formData.phone === '',
          errorMsg: '请填写正确手机号'
        },
        {
          name: 'machineNumber',
          checkType: 'phonenoOther',
          checkRule: '',
          isPassCheck:
            !(this.serviceIncludeScene === 'isHaveInsurance' && this.formData.phoneType === 0) ||
            this.formData.machineNumber === '',
          errorMsg: '请填写正确的其他联系方式'
        }
      ];
      // 购买人信息校验
      if (!graceChecker.check(this.formData, rule)) {
        return graceChecker.error;
      }
      return false;
    },
    // eslint-disable-next-line complexity
    async formSubmit(e) {
      // 基础校验
      if (this.checkRequestFun(e.detail.value)) {
        uni.showToast({ title: this.checkRequestFun(e.detail.value), icon: 'none' });
        return false;
      }
      // 是否阅读协议
      if (!this.argeeBoolean && this.artIdArr && this.artIdArr.length > 0) {
        uni.showToast({ title: '请阅读并同意相关内容', icon: 'none' });
        return false;
      }
      uni.showToast({ title: '加载中', icon: 'loading', duration: 15000, mask: true });
      // 友盟统计
      tongji('104419e9-bcfd-4f5e-8d8c-b6b0dc0e1428');
      const { data: phonePatId } = this.formData.phone
        ? await getPatientIdByIdCard({
            phone: this.formData.phone,
            idCard: ''
          })
        : '';
      console.log('phonePatId:', phonePatId);
      console.log('this.formData:', this.formData);
      if (phonePatId && phonePatId !== this.formData.patientId) {
        uni.showToast({ title: '手机号已存在', icon: 'none' });
        return;
      }
      // 实名校验等大部分情况的校验
      const checkReal = await this.checkRealFun();
      if (checkReal) {
        uni.showToast({ title: checkReal, icon: 'none' });
        return false;
      }
      // 前端校验结束
      let sendData = {
        identity: this.formData.identity,
        name: this.formData.name || undefined,
        idCard: this.formData.idCard || undefined,
        patientId: this.formData.patientId || undefined,
        address: this.formData.address || undefined,
        diseases: this.formData.diseases,
        phone: this.formData.phone || this.isHavePhone || '',
        machineNumber: this.formData.machineNumber || this.isHaveMachineNumber,
        sex: this.formData.sex,
        birthday: this.formData.birthday
      };

      // 新添加家庭成员关系。（自己也要调用此接口，原因忘记了。）
      this.addFUser();
      await sendUserInfoForm(sendData).then((res) => {
        uni.hideToast();
        if (res.code === 0) {
          this.createServiceOrderFun();
          // this.$store.commit('join/SET_STOREFORMDATA', {
          //   ...sendData
          // });
        } else {
          uni.showToast({ title: res.message, icon: 'none' });
        }
      });
    },
    getAgeByIdCard(UUserCard) {
      if (!UUserCard) {
        // 兼容没身份证数据
        return '';
      }
      // 获取年龄
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
      if (
        UUserCard.substring(10, 12) < month ||
        (UUserCard.substring(10, 12) === month && UUserCard.substring(12, 14) <= day)
      ) {
        age++;
      } else if (UUserCard.substring(10, 12) === month && UUserCard.substring(12, 14) === day + 1) {
        age++;
      }
      return age;
    },
    async createServiceOrderFun() {
      const self = this;
      const { data: orderList } = (await getInsuranceOrder(this.loginPatientId, 0, this.formData.patientId)) || null;
      const noPayOrder = orderList.filter((item) => {
        return this.serviceInfo.insurancePackagePros.find(
          (kidItem) => kidItem.id === item.insurancePackageProsId && item.status === 2
        );
      });
      if (noPayOrder && noPayOrder.length > 0) {
        uni.showModal({
          title: '创建服务单失败',
          showCancel: false,
          confirmText: '去支付',
          content: '服务对象已存在该服务的待支付订单，请前往支付。',
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/service/detail?orderId=' + noPayOrder[0].orderId + '&patientId=' + self.loginPatientId
              });
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
        return false;
      }
      // 创建服务单
      // 获取登录人信息
      const loginUser = (await this.getUserInfoByPatientIdFun(this.loginPatientId)) || {};
      const insureUser = this.formData;
      const sendData = {
        insurerId: this.loginPatientId,
        insurerName: loginUser.name,
        insurerPhone: loginUser.phone,
        insurerIdCard: loginUser.idCard,
        insuredId: insureUser.patientId,
        insuredName: insureUser.name,
        insuredPhone: insureUser.phone,
        insuredIdCard: insureUser.idCard,
        birthday: insureUser.birthday,
        sex: insureUser.sex,
        relationWithInsurer: insureUser.identity,
        insurancePackageProsId: this.serviceInfo.insurancePackagePros[0].id, // 保险档次id
        cid: uni.getStorageSync('cid') || '' // 渠道码
      };
      let minAge = this.serviceInfo.minAge;
      let maxAge = this.serviceInfo.maxAge;
      // 对用户年龄添加限制
      let insuredAge = this.getAgeByIdCard(insureUser.idCard) || getAgeByBirthday(insureUser.birthday);
      if (insuredAge < minAge || insuredAge > maxAge) {
        wx.showModal({
          title: '提示',
          content: `超出当前服务限定年龄（${minAge}-${maxAge}岁），无法获取服务`,
          showCancel: false,
          confirmText: '了解详情',
          confirmColor: '#179cd5',
          success: function (res) {
            if (res.confirm) {
              self.$wxPromise.reLaunch({
                // url: '/pages/service/index?patientId=' + insureUser.patientId
                url: '/pages/index/index?patientId=' + insureUser.patientId
              });
            }
          },
          fail: (err) => {
            console.log('弹层报错 err:', err);
          }
        });
        return;
      }
      let { code, data, message } = await createServiceOrder(sendData);
      if (code !== 0) {
        uni.showModal({
          title: '创建服务单失败',
          showCancel: false,
          confirmText: code === 422 ? '去支付' : '确定',
          content:
            code === 422 ? '该服务对象存在待支付的服务订单，请前往支付。' : message || '创建服务单失败，请稍后重试。',
          success: function (res) {
            if (res.confirm) {
              if (code === 422) {
                uni.navigateTo({
                  url: '/pages/service/detail?orderId=' + data + '&patientId=' + self.loginPatientId
                });
              }
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
        // uni.showToast({ title: message || '创建服务单失败', icon: 'none' });
        return false;
      }

      if (data.amount === 0) {
        this.inquiryMixin({
          insuranceServices: this.serviceInfo.insurancePackagePros[0].insuranceServices,
          teamOrderNo: data.insuranceTeamOrderNo,
          insuredId: data.insuredId,
          packageId: this.serviceId,
          orderId: data.insuranceOrderId
        });
        return;
      }
      this.$wxPromise.navigateTo({
        url: '/pagesC/pay/index?orderId=' + data.insuranceOrderId
      });
    },
    // eslint-disable-next-line complexity
    async checkRealFun() {
      let checRealUnPass = false;
      // 通过手机号获取patientId
      const { data: phonePatId } = this.formData.phone
        ? await getPatientIdByIdCard({
            phone: this.formData.phone,
            idCard: ''
          })
        : '';
      // 通过身份证号获取patientId
      const { data: idCardPatId } = this.formData.idCard
        ? await getPatientIdByIdCard({
            idCard: this.formData.idCard,
            phone: ''
          })
        : '';
      if (idCardPatId || phonePatId) {
        this.formData.patientId = idCardPatId || phonePatId;
      } else {
        this.formData.patientId = this.getHistoryPid || '';
      }
      if (await this.checkListoryHave()) {
        return '该用户已存在于关系组中，请勿重复添加。';
      }
      // 如果手机号和身份证都没有patientId，注册新用户
      if (!this.formData.patientId) {
        const bindPatientInfo = {
          phone: this.formData.phone,
          name: this.formData.name,
          idCard: this.formData.idCard,
          hospitalId: hospitalId,
          machineNumber: this.formData.machineNumber || this.formData.phone ? '' : '无',
          cid: uni.getStorageSync('cid') || '',
          source: registerSource
        };
        const { data: newUserData, code: newUserCode, message: newUserMessage } = await bindPatients(bindPatientInfo);
        if (newUserCode === 0 && newUserData) {
          this.formData.patientId = newUserData;
        } else {
          return newUserMessage || '注册新用户失败';
        }
      }
      // 手机号是实名过了，直接返回通过，否则继续下面校验
      const phonePatIdInfo = phonePatId ? await this.getUserInfoByPatientIdFun(phonePatId) : null;
      const idCardPatIdInfo = idCardPatId ? await this.getUserInfoByPatientIdFun(idCardPatId) : null;
      console.log('real this.formData.patientId:', this.formData.patientId);
      console.log('real phonePatIdInfo:', phonePatIdInfo);
      if (phonePatIdInfo && phonePatIdInfo.patientId && phonePatIdInfo.patientId !== this.formData.patientId) {
        checRealUnPass = this.formData.phone + '手机号/身份证号已存在，不可重复创建会员';
        return checRealUnPass;
      }
      if (phonePatIdInfo && idCardPatIdInfo && phonePatId !== idCardPatId) {
        return '手机号和身份证信息不匹配';
      }

      if (
        this.formData.idCard &&
        (this.serviceIncludeScene === 'isHaveInsurance' || this.serviceIncludeScene === 'isHaveInsurDoctorOrPhy') &&
        this.phonePatIdInfo &&
        this.phonePatIdInfo.idCard !== this.formData.idCard
      ) {
        return '用户信息不匹配，请确认身份信息是否正确';
      }
      if (
        this.formData.idCard &&
        (this.serviceIncludeScene === 'isHaveInsurance' || this.serviceIncludeScene === 'isHaveInsurDoctorOrPhy')
      ) {
        await getRealNameResult({
          idCard: this.formData.idCard,
          name: this.formData.name,
          patientId: this.formData.patientId
        }).then((res) => {
          if (res.code !== 0) {
            checRealUnPass = '请做实名校验！';
            return checRealUnPass;
          }
        });
      }
      if (
        (phonePatIdInfo && phonePatIdInfo.realNameAuthenticationPassed === 1) ||
        (idCardPatIdInfo && idCardPatIdInfo.realNameAuthenticationPassed === 1)
      ) {
        this.isAuthen = true;
        return false;
      }
      return checRealUnPass;
    },
    addFUser() {
      const data = {
        patientId: this.loginPatientId,
        memberId: this.formData.patientId,
        relation: this.formData.identity
      };
      addFamilyMember(data);
    },
    choseSex(id) {
      this.formData.sex = id;
    },
    chosePhoneType(id) {
      this.formData.phoneType = id;
    },
    addressFormatTrsf(val) {
      let item = [];
      if (Object.prototype.toString.call(val) === '[object Object]' && val.cityId) {
        item = [val.provinceId, val.cityId, val.areaId];
        return item;
      }
      return val;
    },
    async checkListoryHave() {
      let isHaveFamily = this.familyUserData.some(
        (item) =>
          (item.memberId === this.formData.patientId && item.relation !== this.formData.identity) ||
          (item.memberId === this.formData.patientId &&
            item.relation === this.formData.identity &&
            this.isAddType &&
            this.formData.identity !== 1)
      );
      if (
        (wx.getStorageSync('patientid') === this.formData.paitentId && this.formData.identity !== 1) ||
        isHaveFamily
      ) {
        return '该用户已存在于关系组中，请勿重复添加。';
      }
      return false;
    },
    async getUserInfoByPatientIdFun(patientId) {
      const { data } = await getUserInfoByPatientId(patientId);
      return data;
    },
    readArticle() {
      if (this.argeeBoolean) {
        this.argeeBoolean = !this.argeeBoolean;
        return;
      }
      this.$refs.artScroll.editIndexCur();
      this.articlePop = true;
    },
    artPopCenter(val) {
      this.articlePop = false;
      this.agree = val;
      this.argeeBoolean = true;
    },
    getArticleTitle(item) {
      this.artTitleArr = [...item];
      console.log(this.artTitleArr);
    }
  }
};
</script>
<style>
page {
  background-color: #f4f4f4;
}
.uni-btn-v button {
  border: none !important;
}
button:after {
  border: none !important;
}
.phcolor {
  color: rgba(0, 0, 0, 0.3);
}
</style>

<style lang="scss">
.home {
  padding-bottom: calc(88rpx + 40rpx + constant(safe-area-inset-bottom) + 60rpx);
  padding-bottom: calc(88rpx + 40rpx + env(safe-area-inset-bottom) + 60rpx);
  @supports not (constant(safe-area-inset-bottom)) {
    padding-bottom: 180rpx;
  }
  padding-bottom: 220rpx !important;
}
.box {
  padding: 20px;
}
.banner {
  width: 750rpx;
  height: 380rpx;
  /* border: 2rpx solid rgba(0, 0, 0, 0); */
  /* background: linear-gradient(186deg, #fd8d8d 0%, #f63434 100%); */
  background: #f96a6a;
}
.bannerParent {
  position: relative;
  height: 100%;
  width: 100%;
}
.banner .one {
  font-size: 48rpx;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  position: absolute;
  left: 50rpx;
  top: 78rpx;
  z-index: 9;
}
.banner .two {
  position: absolute;
  font-size: 56rpx;
  font-weight: bold;
  color: #ffe6b3;
  left: 50rpx;
  top: 150rpx;
  z-index: 9;
}
.banner .icon {
  position: absolute;
  right: 24rpx;
  top: 30rpx;
  width: 300rpx;
  height: 230rpx;
}
.banner .icon img {
  width: 300rpx;
  height: 230rpx;
}

.getPhoneBtn {
  color: #fff;
  width: 700rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 24rpx;
  font-size: 36rpx;
  margin-top: 100rpx;
  background: -moz-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fe894d), color-stop(100%, #ef3931));
  background: -webkit-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -o-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -ms-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: linear-gradient(to bottom, #fe894d 0%, #ef3931 100%);
}
.disBlockBox {
  font-size: 28rpx;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 0 auto;
  text-align: center;
  min-height: 86rpx;
}
.disBlockBox .disBlockKid {
  display: inline-block;
  position: relative;
  border: 2rpx solid #707070;
  width: 104rpx;
  margin-right: 14rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  opacity: 0.85;
  height: 64rpx;
  line-height: 64rpx;
}
.chose {
  border: 2rpx solid #f34e1c !important;
  color: #f34e1c;
}
.chose .disBlock {
  opacity: 1 !important;
}
.choseImg {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 36rpx;
  height: 36rpx;
}
.disBlockBox .disBlockKid:last-child {
  margin-right: 0;
}
.disBlockBox .disBlockKid:first-child {
  margin-left: 0;
}
.disBlockKid .cur {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 40rpx;
  height: 40rpx;
}
.disBlockKid .cur img {
  width: 100%;
  height: 100%;
}
.disBlockBox .disBlockKid .disBlock {
  display: inline-block;
  width: 100%;
  text-align: center;
}
.userIcon img {
  width: 100rpx;
  height: 100rpx;
  border-radius: 120rpx;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.userIcon {
  width: 100rpx;
  height: 100rpx;
  padding: 10rpx 0;
  position: relative;
  background-color: #e5edfe;
  border-radius: 120rpx;
}
.orgColor {
  background: rgba(254, 236, 215, 1);
}
.marginTB20 {
  margin: 15rpx 0;
}
.content {
  padding: 40rpx;
  border-radius: 24rpx;
  background-color: #fff;
  margin: 24rpx 24rpx 24rpx 24rpx;
  /* box-shadow: 0px 12px 12px #e8e8e8; */
}
.marginTop-40 {
  margin-top: -120rpx;
}
.marginTop40 {
  margin-top: 40rpx;
}
.marginBottom20 {
  margin-bottom: 20rpx !important;
}
.paddingBotNone {
  padding-bottom: 12rpx;
}
.content .title {
  font-size: 36rpx;
  margin-bottom: 40rpx;
}
.lineHeight86 {
  height: 86rpx;
  line-height: 86rpx;
}
.size28 {
  font-size: 28rpx;
}
.inputBox {
  border-bottom: 1px solid #e8e8e8;
  font-size: 28rpx;
  position: relative;
  padding: 10rpx 0;
}
.inputBox:last-child {
  border: none;
}
.clearInp {
  position: absolute;
  right: 0;
  top: 16rpx;
  z-index: 99;
  display: inline-block;
  width: 80rpx;
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
}
.clearInp img {
  width: 28rpx;
  height: 28rpx;
}
.idAuthen {
  position: absolute;
  right: 80rpx;
  top: 38rpx;
  z-index: 99;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.3);
  width: 64rpx;
  height: 32rpx;
  line-height: 32rpx;
  border-radius: 4rpx;
  text-align: center;
  color: #fff;
  font-size: 24rpx;
}
.inputBox .title {
  float: left;
}
.inputBox .name {
  float: left;
  width: 140rpx;
}
.inputBox .uni-input {
  float: left;
  width: 420rpx;
  color: rgba(0, 0, 0, 0.55);
}
.clear {
  clear: both;
  overflow: hidden;
  zoom: 1;
  height: 0px;
}
.marginTop20 {
  margin-top: 20rpx;
}
.city {
  color: rgba(0, 0, 0, 0.55);
  font-size: 28rpx;
  position: relative;
}
.rightIcon {
  position: absolute;
  right: 0rpx;
  top: 2rpx;
}
.rightIcon img {
  width: 48rpx;
  height: 48rpx;
}
.uni-btn-v button {
  width: 702rpx;
  height: 88rpx;
  border: 2rpx solid rgba(0, 0, 0, 0);
  background: linear-gradient(236deg, #fe894d 0%, #ef3931 100%);
  opacity: 1;
  border-radius: 44rpx;
  color: #fff;
  font-size: 36rpx;
}
.userHistory {
  color: rgba(0, 0, 0, 0.5);
  margin: 24rpx 0;
}
.userHistory .spans {
  display: inline-block;
  padding: 4rpx 24rpx;
  font-size: 28rpx;
  background-color: #f3f3f3;
  color: rgba(0, 0, 0, 0.55);
  border-radius: 28rpx;
  margin-right: 20rpx;
  margin-left: 10rpx;
  margin-bottom: 10rpx;
}
.historyCur {
  background: rgba(239, 57, 49, 0.6) !important;
  color: #fff !important;
}
.marginBot20 {
  margin-bottom: 20rpx;
}
.wordTitle {
  color: rgba(0, 0, 0, 0.55);
}
.wordColorBlack {
  color: #333;
}

.footbox {
  margin-top: 20rpx;

  background-color: #fff;
  padding: 40rpx;
}
.blue {
  color: #418dc7;
}
.noClick {
  pointer-events: none;
}
.uni-list-cell-db {
  .uni-input {
    height: 80rpx;
    line-height: 80rpx;
  }
}
.marginBottom20 {
  margin-bottom: 20rpx;
}
.grey {
  color: rgba(0, 0, 0, 0.3);
}
.pointNone {
  pointer-events: none;
  .sickBox {
    color: #999;
  }
  .uni-input {
    color: #999;
  }
}
.textLeft {
  text-align: left !important;
}
.sickBox {
  font-size: 28rpx;
  margin: 0 auto;
  float: left;
  margin-top: 10rpx;
}
.sickBtn {
  display: inline-block;
  min-width: 104rpx;
  padding: 0 15rpx;
  text-align: center;
  height: 64rpx;
  line-height: 64rpx;
  border: 2rpx solid #b2b2b2;
  margin-right: 14rpx;
  border-radius: 16rpx;
  position: relative;
}
.chose {
  border: 2rpx solid #f25559;
  color: #f25559;
}
.sickBtn .cur {
  position: absolute;
  right: 0;
  bottom: 0;
}
.sickBtn .cur {
  width: 46rpx;
  height: 46rpx;
}
.sickBtn .cur img {
  width: 100%;
  height: 100%;
}
.sickBtn:first-child {
  margin-left: 0;
}
.sickBtn:last-child {
  margin-right: 0;
}
</style>
<style lang="scss">
.home {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
.inputIcon {
  position: absolute;
  right: 10rpx;
  top: 50%;
  margin-top: -26rpx;
  img {
    width: 40rpx;
    height: 40rpx;
  }
}

.indentContent {
  padding-left: 140rpx;
  position: relative;
  border-bottom: 2rpx solid #e8e8e8;
  .indentTitle {
    position: absolute;
    left: 0;
    top: 20rpx;
  }
}
.tips {
  color: #b5b5b5;
  margin: 18rpx 0;
  font-size: 26rpx;
}
.tellNum {
  padding-left: 6rpx;
}
.pickStyle {
  min-height: 86rpx;
  width: 100%;
  position: relative;
}
</style>
